package 线程;

import lombok.SneakyThrows;

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class _2循环打印从0至100_semaphore {

    public static void main(String[] args) {
        Solution solution = new Solution(3);
        solution.print();
    }

    public static class Solution {
        AtomicInteger integer = new AtomicInteger(0);
        Semaphore semaphore = new Semaphore(1);
        int N;

        public Solution(int n) {
            this.N = n;
        }
        public void print() {
            for (int i = 0; i < N; i++) {
                printThread printThread = new printThread(i);
                printThread.start();
            }
        }

        class printThread extends Thread {
            int count;

            public printThread(int name) {
                super("thread" + name);
                count = name;
            }

            @SneakyThrows
            @Override
            public void run() {
                while (integer.get() <= 100) {
                    if (integer.get() % N == this.count) {
                        semaphore.acquire();
                        if (integer.get() <= 100) {
                            System.out.println(this.getName() + ":" + integer.getAndIncrement());
                        }
                        semaphore.release();
                    }
                }

            }
        }
    }
}
